import React, { useEffect, useState } from 'react';
import { Descriptions, Modal, Divider, Button, Table } from 'antd'
import { isNull, showMsg } from '@/utils/utils';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { getPlanOrderDetail, getFeeDetailGoodsList, printOrderPlanCollect } from '@/services/order/api';
import { print } from '@/utils/utils'; 
import './style.less';
import moment from 'moment';

const BillStatus = {
  U: '未出账',
  F: '已出账',
  D: '已删除'
}

const SettStatus = {
  U: '未结算',
  W: '待结算',
  P: '已结算',
  G: '结算中'
}

const FeeDetailDialog: React.FC<any> = (props) => {
  const { 
    order_id,
    searchParams = {},
    handleModalVisible,
    detail = {}, // 计划订单详情
    type = '', // 打印类型，按条件/明细
  } = props;

  
  const columns: ProColumns<STOCKGOODSAPI.GoodsItem>[] = [
    {
      title: '账单日期',
      dataIndex: 'bill_date',
      width: 90,
      hideInTable: type === '1',
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      width: 200
    },
    {
      title: '规格（单位）',
      dataIndex: 'specs_name',
      width: 100
    },
    {
      title: '单价',
      dataIndex: 'goods_price',
      width: 80,
      valueType: 'money',
      align: 'right'
    },
    // {
    //   title: '数量',
    //   dataIndex: 'total_num',
    //   align: 'right',
    //   width: 60,
    //   render: (dom, entity) => {
    //     return type === '1' ? dom : `${entity.check_num === -1 ? entity.bill_num : entity.check_num}`
    //   }
    // },
    {
      title: '计划用量',
      dataIndex: 'total_bill_num',
      align: 'right',
      width: 60,
      render: (dom, entity) => {
        return type === '1' ? dom :  entity.bill_num
      }
    },
    {
      title: '核定用量',
      dataIndex: 'total_num',
      align: 'right',
      width: 60,
      render: (dom, record) => type === '1' ? dom : record.check_num === -1 ? record.bill_num : record.check_num
    },
    {
      title: '账单费用',
      dataIndex: 'total_price',
      width: 120,
      valueType: 'money',
      align: 'right',
      render: (dom, record) => type === '1' ? dom : `￥${record.bill_price}`,
    },
    {
      title: '已结算费用',
      dataIndex: 'pay_total_price',
      width: 130,
      valueType: 'money',
      align: 'right',
      hideInTable: type === '2',
    },
    {
      title: '待结算费用',
      dataIndex: 'wait_total_price',
      width: 130,
      valueType: 'money',
      align: 'right',
      hideInTable: type === '2',
      render: (val, record) => {
        return '￥' + parseFloat(parseFloat(record.total_price) - parseFloat(record.pay_total_price)).toFixed(2)
      }
    },
    {
      title: '结算状态',
      dataIndex: 'sett_status',
      valueType: 'select',
      valueEnum: {
        U: '未结算',
        W: '待结算',
        P: '已结算',
        G: '结算中'
      },
      width: 150,
      align: 'right',
      hideInTable: type === '1',
    },
  ]

  useEffect(() => {
    if (order_id) {
      setTimeout(() => {
        print(document.querySelector('.fee-deatial-dialog .ant-modal-body'), {
          size: 'portrait'
        });
      }, 500)
    }
  }, [order_id])


  return <Modal
      width="90%"
      maskClosable={false}
      className="fee-deatial-dialog"
      onCancel={() => handleModalVisible(false)}
      footer={null}
      visible>
      <div className="dialog">
        <h2 className="tc">{type === '1' ? '费用汇总' : '费用明细'}</h2>
        <Divider />
        <div>1.账单信息</div>
        <Divider />
        <Descriptions className="bill-info-list" column={4}>
          <Descriptions.Item label="姓名">
            {detail.patient_name}
          </Descriptions.Item>
          <Descriptions.Item label="住院号/身份证号">
            { detail.admission_num || detail.identity_no}
          </Descriptions.Item>
          <Descriptions.Item label="账单周期">
            {searchParams.begin_date ? moment(searchParams.begin_date).format('YYYY-MM-DD') : ''} - {searchParams.end_date ? moment(searchParams.end_date).format('YYYY-MM-DD') : ''}
          </Descriptions.Item>
          <Descriptions.Item label="账单金额">
            ¥{detail.out_price}
          </Descriptions.Item>
          
          <Descriptions.Item label="商品名称">
            {searchParams.goods_name || '(全部)'}
          </Descriptions.Item>
          <Descriptions.Item label="账单状态">
            {BillStatus[searchParams.bill_status]  || '(全部)'}
          </Descriptions.Item>
          <Descriptions.Item label="结算状态">
            {SettStatus[searchParams.sett_status] || '(全部)'}
          </Descriptions.Item>
          {detail.create_dept_code === '11232300' && <Descriptions.Item label="取货地址">生活服务楼三楼314号房</Descriptions.Item>}
        </Descriptions>
       
        <div>2.费用记录</div>
        
        <Divider style={{margin: '10px 0 0'}} />

        <ProTable<STOCKGOODSAPI.GoodsItem> 
          // rowKey={(record) => type === '1' ? `${record.goods_id}_${new Date().getTime()}` : `${record.bill_id}_${new Date().getTime()}`}
          options={false}
          search={false}
          columns={columns}
          pagination={false}
          request={async (params) => {
            try {
              params = {
                ...searchParams,
                order_id,
                current: 1,
                pageSize: 999999,
              }
              // printOrderPlanCollect
              const data = type === '1' ? await getFeeDetailGoodsList(params) : await printOrderPlanCollect(params)
              let list = Object.assign([], data.record_list);

              if (type === '2') {
                list = list.filter((item) => item.check_num !== 0)
              } else {
                list = list.filter((item) => item.total_num > 0)
              }
              console.log('list', list, type)
              return {
                data: list,
                total: list.length,
                success: true
              }
            } catch (error) {
              return {
                total: 0,
                data: []
              }
            }
          }}
          bordered
          summary={pageData => {
            let totalPrice = 0;
            let total = 0;
            let yjs = 0;
            let djs = 0;

            pageData.forEach(({ total_price, bill_price, total_num, check_num, bill_num, pay_total_price, sett_status }) => {
              totalPrice += parseFloat(total_price || bill_price);
              // 汇总
              if (type === '1') {
                total += total_num;
                yjs += parseFloat(pay_total_price);
                djs += parseFloat(total_price) - parseFloat(pay_total_price);
              } else { // 详情
                total += check_num === -1 ? bill_num : check_num;
                if (sett_status === 'P') { // 已结算
                  yjs += parseFloat(bill_price);
                } else {
                  djs += parseFloat(bill_price);
                }
              }
              
            });
            return (
              <>
                <Table.Summary.Row>
                  {
                    type === '2' && <Table.Summary.Cell colSpan={5}><span style={{ fontWeight: 'bold' }}>合计</span></Table.Summary.Cell>
                  }
                  <Table.Summary.Cell colSpan={type === '2' ? 0 : 4} align='left'><span style={{ fontWeight: 'bold' }}>合计</span></Table.Summary.Cell>
                  <Table.Summary.Cell align='right'>
                    <span>{total}</span>
                  </Table.Summary.Cell>
                  <Table.Summary.Cell align='right'>
                    <span type="danger">￥{parseFloat(totalPrice).toFixed(2)}</span>
                  </Table.Summary.Cell>
                  {
                    type === '1' ?
                    <>
                      <Table.Summary.Cell align='right'>
                        <span>￥{parseFloat(yjs).toFixed(2)}</span>
                      </Table.Summary.Cell>
                      <Table.Summary.Cell align='right'>
                        <span>￥{parseFloat(djs).toFixed(2)}</span>
                      </Table.Summary.Cell>
                    </> :
                    <Table.Summary.Cell align='right'>
                      <div><span>￥{parseFloat(djs).toFixed(2)} / ￥{parseFloat(yjs).toFixed(2)}</span></div>
                      <div><span>（未结算 / 已结算）</span></div>
                    </Table.Summary.Cell>
                  }
                </Table.Summary.Row>
              </>
            )
          }}
        />
      </div>
    </Modal>
}
export default FeeDetailDialog;
